<?php

namespace app\helper;

trait SqlTraits {

    public static function searchFile($file) {
        if (is_readable($file)) {
            return $file;
        }elseif (is_readable(CURRENT_DIR.'/'.$file)) {
            return CURRENT_DIR.'/'.$file;
        }elseif (is_readable(CURRENT_DIR.'/sql/' . $file)) {
            return CURRENT_DIR.'/sql/' . $file;
        }else{
            return '';
        }
    }

    public static function parseFile($filepath) { 
        $app_db_name = '';
        $sql_content = preg_replace_callback('/use\s+(`|)?(\w+[-_]\w+)\1\s*;/i', function($matchs) use (&$app_db_name){
            $app_db_name = $matchs[2];
            return '';
        }, file_get_contents($filepath));

        $sql_content = preg_replace_callback('/(`|)?'.preg_quote($app_db_name,'/').'\1\./i', function($matchs) {
            return '';
        }, $sql_content);

        $sql_content = preg_replace_callback('/SET\s+FOREIGN_KEY_CHECKS\s?=\s?0\s?;/i', function($matchs) {
            return '';
        }, $sql_content);
        return trim($sql_content);
    }

}
